#include <T3SRApp.h>
#include <obj_parser.h>
#include <mat4.h>
#include <utility_math.h>
#include <debug.h>
#include <log.h>
#include <filesystem>
#include <logImGui.h>
#include <config.h>

T3SRApp::T3SRApp(int argc, char** argv) {
    std::filesystem::path configFilePath = parseCmdLine(argc, argv);

    config.windowConfig.width = mWindowManager.width;
    config.windowConfig.height = mWindowManager.height;
    
    CheckFunc(SDL_Init(SDL_INIT_EVERYTHING));

    mSceneManager.createScene(configFilePath);
}

std::filesystem::path T3SRApp::parseCmdLine(int argc, char** argv) {
    std::filesystem::path configFilePath;
    if (argc == 1) {
        configFilePath = "C:\\GraphicsDev\\software-renderer\\res\\cube\\cube.t3sr";
    }
    else {
        for (int i = 1; i < argc; ++i) {
            std::string_view args(argv[i]);
            if (args == "--help") {
                printf("--file <path-to-config-file> = specify a t3sr config file\n");
                terminate();
            }
            else if (args == "--default") {
                configFilePath = "res\\cube\\cube.t3sr";
                break;
            }
            else if (args == "--file") {
                ++i;
                if (i < argc) {
                    configFilePath = argv[i];
                    break;
                }
                else {
                    printf("no t3sr config file specify for --file\n" 
                           "please run 't3sr --help' for all supported options\n");
                    abort();
                }
            }
            else {
                printf("unknown argument\n"
                       "please run 't3sr --help' for all supported options\n");
                abort();
            }
        }
    }
    return configFilePath;
}

void T3SRApp::Run() {
    bool isQuit = false;

    while (!isQuit) {
        mTimer.tick();

        mWindowManager.newFrame();

        mFrameBuffer.clear();
        isQuit = mInputManager.pollEvent(secondCast(mTimer));

        ImGui::Begin("Configure");
            ImGui::Text("Texture Simple Method");
            ImGui::RadioButton("Nearest", &config.textureConfig.method, (int)TextureConfig::SimpleMethod::nearest);
            ImGui::SameLine();
            ImGui::RadioButton("Bilinear", &config.textureConfig.method, (int)TextureConfig::SimpleMethod::bilinear);
            //ImGui::SameLine();
            //ImGui::RadioButton("Trilinear", &config.textureConfig.method, (int)TextureConfig::SimpleMethod::trilinear);
        ImGui::End();

        mSceneManager.draw(mFrameBuffer, mInputManager.camera.position);
        mWindowManager.swap(mFrameBuffer.getPixelColorPtr());

        printf("this frame take %lldus FPS: %f\n", mTimer.getDeltaTime(), 1000000.0f / (float)mTimer.getDeltaTime());
    }
}

T3SRApp::~T3SRApp() {
    SDL_Quit();
}